import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoServer {
    Socket socket = null;

    public TcpEchoServer() throws IOException {
        //连接服务器的端口和IP地址
        socket = new Socket("127.0.0.1",2000);
    }

    public void stack() throws IOException {
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            Scanner scanNext = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
           while(true) {
               //从控制台读取请求
               System.out.print(">:");
               String str = scanner.next();
               //向服务器发送请求
               writer.println(str);
               writer.flush();
               //读取响应数据
               String str1 = scanNext.next();
               //打印请求响应信息
               System.out.printf("[%s:%d] 请求:%s 响应:%s \n",socket.getInetAddress().toString(),socket.getPort()
               ,str,str1);
           }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer();
        server.stack();
    }
}
